package com.example.demo;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RequestMapping("/request")
@RestController
public class RequestController {
    @RequestMapping("/getCookie")
    public String getCookie(HttpServletRequest request) {
        //获得全部cookie
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            System.out.println(cookie.getName()+":"+cookie.getValue());
        }
        return "success 获得cookie成功";
    }
    @RequestMapping("/getCookie2")
    public String getCookie2(@CookieValue("bite") String bite){
        return "bite:"+bite;
    }
    @RequestMapping("/getSession")
    public String getSession(HttpServletRequest request){
        HttpSession session = request.getSession();
        String userName = (String)session.getAttribute("userName");
        return "登录用户:"+userName;
    }

    @RequestMapping("/getSession2")
    public String getSession(HttpSession session){
        //如果没有这个session的话，会自动分配一个session然后，不会导致空指针，然后所拿到值就是一个空指针
        String userName = (String)session.getAttribute("userName");
        return "登录用户:"+userName;
    }

    @RequestMapping("/getSession3")
    public String getSession(@SessionAttribute(value = "userName", required = false) String userName){
        return "登录用户:"+userName;
    }

    @RequestMapping("/getHeader")
    public String getHeader(HttpServletRequest request){
        String userAgent = request.getHeader("User-Agent");
        return "userAgent:"+userAgent;
    }

    @RequestMapping("/getHeader2")
    public String getHeader2(@RequestHeader("User-Agent") String userAgent){
        return "userAgent:"+userAgent;
    }
}
